package com.a01_2021.thousandstimes.saas.service.impl;

import com.a01_2021.thousandstimes.exception.CustomException;
import com.a01_2021.thousandstimes.exception.CustomExceptionType;
import com.a01_2021.thousandstimes.general.service.SysUserService;
import com.a01_2021.thousandstimes.saas.entity.Authorization;
import com.a01_2021.thousandstimes.saas.mapper.AuthorizationMapper;
import com.a01_2021.thousandstimes.saas.service.AuthorizationService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author FRQ
 * @since 2021-02-22
 */
@Service
public class AuthorizationServiceImpl extends ServiceImpl<AuthorizationMapper, Authorization> implements AuthorizationService {

    @Resource
    AuthorizationMapper authorizationMapper;

    @Resource
    SysUserService sysUserService;

    /**
     * 通过用户id查询授权
     * @param userId 用户id
     * @return Authorization
     * @throws CustomException 抛出自定义异常
     */
    public Authorization getAuthorizedFromUserId(long userId) throws CustomException {
        QueryWrapper<Authorization> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        Authorization authorization = authorizationMapper.selectOne(queryWrapper);
        if(authorization==null){
            throw new CustomException(CustomExceptionType.AUTHENTICATION_NOT_FOUND,"找不到授权");
        }
        return authorization;
    }

    /**
     *通过用户id授权
     * @param userId 用户id
     * @return Authentication返还授权的情况
     */
    @Override
    public Authorization authorization(long userId) throws CustomException {
        if(!sysUserService.isUser(userId))
            throw new CustomException(CustomExceptionType.USER_NOT_FOUND_ERROR,"无此用户 ");
        Authorization authorization=new Authorization();
        authorization.setUserId(userId);
        authorization.setTime(LocalDateTime.now());
        authorizationMapper.insert(authorization);
        return authorization;
    }
}
